package com.pingancar.creditmanage.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by liymm on 2015-03-03.
 */
public class InitListener implements ServletContextListener {

    Timer accessTokenTimer;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        int period = getAccessToken();

        accessTokenTimer = new Timer();
        accessTokenTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                getAccessToken();
                getJsAPITicket();
            }

        }, 0, period*1000);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        accessTokenTimer.cancel();
    }

    static final String APPID = "wx47ff0c58fec26a68";
    static final String APPSECRET = "d23564f35f7fb71a0712d5d71456627e";
    static AccessToken at;
    static Ticket ticket;



    int getAccessToken() {
        String url = String
                .format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                        APPID, APPSECRET);

        String resp = HttpHelper.httpsGet(url);

        try {
            at = new ObjectMapper().readValue(resp, AccessToken.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("AT: " + at.getAccess_token());

        return at.getExpires_in();
    }

    void getJsAPITicket() {
        String url = String
                .format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",
                        at.getAccess_token());
        String resp = HttpHelper.httpsGet(url);

        try {
            ticket = new ObjectMapper().readValue(resp, Ticket.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Ticket: " + ticket.getTicket());
    }

    public static Signature getSignature(String url) {
        if (at == null)
            return null;

        if (ticket == null)
            return null;

        Signature s = new Signature();
        s.setTimestamp(System.currentTimeMillis() / 1000);
        s.setNoncestr("random string");


        String src = String.format("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s",
                ticket.getTicket(), s.getNoncestr(), s.getTimestamp(), url);

        s.setSignature(Algorithm.SHA1(src));

        System.out.println(ticket.getTicket());
        System.out.println(s.getNoncestr());
        System.out.println(s.getTimestamp());

        return s;
    }
}
